package org.zoomdev.zoom.dao.executor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zoomdev.zoom.dao.DaoException;
import org.zoomdev.zoom.dao.SqlConfig;
import org.zoomdev.zoom.dao.configs.Update;
import org.zoomdev.zoom.dao.configs.Where;
import org.zoomdev.zoom.dao.entity.Entity;
import org.zoomdev.zoom.dao.modules.CoreDaoModule;
import org.zoomdev.zoom.dao.utils.LogUtils;

import java.sql.Connection;
import java.sql.SQLException;

public class BatchUpdateExecutor implements SqlExecutor {
    private static final Logger log = LoggerFactory.getLogger(CoreDaoModule.NAME);

    @Override
    public int execute(SqlConfig cfg, Object item) {
        Update update = cfg.getUpdate();
        Where where = cfg.getWhere();
        Entity entity = cfg.getEntity();
        update.clear();
        where.clear();
        update.prepare(cfg, entity, item, cfg.isIgnoreNull());
        String sql = update.buildSql(cfg, where);
        if (CoreDaoModule.logSql) {
            log.info(LogUtils.getSql(sql, update.getParameterValues(where)));
        }
        try {
            Connection conn = cfg.openConnection();
            SqlConfig.BatchConfig stmt = cfg.prepareStatement(conn, sql);
            int n = update.setParameter(stmt.stmt, 1);
            where.setParameter(stmt.stmt, n);
            stmt.addBatch(item);

        } catch (SQLException e) {
            throw new DaoException("执行update失败", e);
        }
        return 0;
    }
}
